package com.atgm.mall.gmmailware.service.impl;

import com.atgm.common.constant.WareConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.WareException;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.mall.gmmailware.dao.WareGameDao;
import com.atgm.mall.gmmailware.dao.WareOrderTaskDao;
import com.atgm.mall.gmmailware.dao.WareOrderTaskDetailDao;
import com.atgm.mall.gmmailware.entity.WareGameEntity;
import com.atgm.mall.gmmailware.entity.WareOrderTaskDetailEntity;
import com.atgm.mall.gmmailware.entity.WareOrderTaskEntity;
import com.atgm.mall.gmmailware.service.WareGameService;
import com.atgm.mall.gmmailware.service.WareOrderTaskDetailService;
import com.atgm.mall.gmmailware.vo.req.WareGameItemVo;
import com.atgm.mall.gmmailware.vo.req.WareGameReqVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.quartz.spi.ThreadExecutor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WareGameServiceImpl extends ServiceImpl<WareGameDao, WareGameEntity> implements WareGameService {

    @Autowired
    private WareOrderTaskDao wareOrderTaskDao;

    @Autowired
    private WareOrderTaskDetailDao wareOrderTaskDetailDao;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    @GlobalTransactional
    public void lockOrderInfo(WareGameReqVo wareGameReqVo) {
        //1、添加库存工作单
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareGameReqVo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        int count = wareOrderTaskDao.insert(wareOrderTaskEntity);
        if (count != 1) {
            log.error("添加库存工作单失败");
            throw new WareException("添加库存工作单失败", BizCodeEnume.SUBMIT_ORDER_FAIL.getCode());
        }

        //2、添加工作单项
        saveTaskDeatil(wareGameReqVo.getList(), wareOrderTaskEntity.getId());

        //3、锁定库存
        lockStock(wareGameReqVo.getList());

    }

    @Override
    @GlobalTransactional
    public void unlockOrderInfo(String orderSn) {
        QueryWrapper<WareOrderTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn", orderSn);
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskDao.selectOne(queryWrapper);

        QueryWrapper<WareOrderTaskDetailEntity> wareOrderTaskDetailEntityQueryWrapper = new QueryWrapper<>();
        wareOrderTaskDetailEntityQueryWrapper.eq("task_id", wareOrderTaskEntity.getId());
        List<WareOrderTaskDetailEntity> orderTaskDetailEntities = wareOrderTaskDetailDao.selectList(wareOrderTaskDetailEntityQueryWrapper);

        List<WareOrderTaskDetailEntity> list = new ArrayList<>(orderTaskDetailEntities.size());
        orderTaskDetailEntities.forEach(item -> {
            WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
            wareOrderTaskDetailEntity.setId(item.getId());
            wareOrderTaskDetailEntity.setLockStatus(2);  //已解锁
            list.add(wareOrderTaskDetailEntity);
        });

        wareOrderTaskDetailService.updateBatchById(list);

        //减少锁定库存
        List<Long> gameIds = orderTaskDetailEntities.stream().map(WareOrderTaskDetailEntity::getSkuId).collect(Collectors.toList());
        unlockStock(gameIds);

    }

    /**
     * 批量保存库存单项
     * @param list
     */
    private void saveTaskDeatil(List<WareGameItemVo> list, Long taskId) {
        List<WareOrderTaskDetailEntity> orderTaskDetailEntities = new ArrayList<>(5);
        list.forEach(wareGameItemVo -> {
            WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
            wareOrderTaskDetailEntity.setTaskId(taskId);
            wareOrderTaskDetailEntity.setSkuId(wareGameItemVo.getGameId());
            wareOrderTaskDetailEntity.setSkuName(wareGameItemVo.getGameName());
            wareOrderTaskDetailEntity.setSkuNum(1);
            wareGameItemVo.setStock(wareGameItemVo.getStock());
            wareOrderTaskDetailEntity.setLockStatus(WareConstant.OrderTaskDetailStatusEnum.LOCKED.getCode());   //锁定状态：
            orderTaskDetailEntities.add(wareOrderTaskDetailEntity);
        });
        wareOrderTaskDetailService.saveBatch(orderTaskDetailEntities);
    }

    /**
     * 锁定库存数量
     * @param list
     */
    private void lockStock(List<WareGameItemVo> list) {
        if (GmMallUtils.isNotEmpty(list)) {
            list.forEach(wareGameItemVo -> {
                baseMapper.lockStock(wareGameItemVo);
            });
        }
    }

    /**
     * 解锁库存数量
     * @param gameIds
     */
    private void unlockStock(List<Long> gameIds) {
        if (GmMallUtils.isNotEmpty(gameIds)) {
            gameIds.forEach(gameId -> {
                baseMapper.unlockStock(gameId);
            });
        }
    }

}
